﻿#include "qrgenerator.h"

QRgenerator::QRgenerator(QObject *parent)
    : QObject{parent}
{
    setAutoDelete(true);
}
QRgenerator::QRgenerator(QObject *parent, QString content, QString name, QRect size, QColor color, QColor bgColor)
    :qrContent(content), saveName(name), imgSize(size), qrColor(color), backgroundColor(bgColor)
{
    setAutoDelete(true);
}

void QRgenerator::setContent(QString content)
{
    qrContent = content;
}

void QRgenerator::setSize(QRect size)
{
    imgSize = size;
}
void QRgenerator::setQRColor(QColor color)
{
    qrColor = color;
}
void QRgenerator::setBGColor(QColor bgColor)
{
    backgroundColor = bgColor;
}
void QRgenerator::setSaveName(QString name)
{
    saveName = name;
}
QImage QRgenerator::GenerateQImage()
{
    QRcode *qrcode;

    qrcode=QRcode_encodeString(qrContent.toLocal8Bit().data(),2,QR_ECLEVEL_Q,QR_MODE_8,1);

    qint32 temp_width=imgSize.width();
    qint32 temp_height=imgSize.height();

    qint32 qrcode_width=qrcode->width>0?qrcode->width:1;
    double scale_x=(double)temp_width/(double)qrcode_width;
    double scale_y=(double)temp_height/(double)qrcode_width;

    QImage mainimg=QImage(temp_width,temp_height,QImage::Format_ARGB32);
    QPainter painter(&mainimg);
    painter.setBrush(backgroundColor);
    painter.setPen(Qt::NoPen);
    painter.drawRect(0,0,temp_width,temp_height);
    painter.setBrush(qrColor);
    for(qint32 y=0;y<qrcode_width;y++)
    {
        for(qint32 x=0;x<qrcode_width;x++)
        {
            unsigned char b=qrcode->data[y*qrcode_width+x];
            if(b &0x01)
            {
             QRectF r(x*scale_x,y*scale_y,scale_x,scale_y);
             painter.drawRects(&r,1);
            }
        }
    }
    return mainimg;
}

QPixmap QRgenerator::GenerateQPixmap()
{
    QPixmap mainmap = QPixmap::fromImage(GenerateQImage());
    return mainmap;
}

void QRgenerator::saveToFile()
{
    QImage objImage = GenerateQImage();
    objImage.save(saveName + ".jpg", "JPEG");
}

void QRgenerator::run()
{
    QImage objImage = GenerateQImage();
    if(saveName.endsWith("jpg"))
        objImage.save(saveName, "JPEG");
    else if(saveName.endsWith("png"))
        objImage.save(saveName, "PNG");
    emit finishGen();
}
